<?php

namespace api\controller;

use common\controller\VerifyController;
use common\service\StepReviewWorkflowRelationService;
use common\validate\StepReviewWorkflowRelation;
use support\ErrorCode;
use think\Request;

class StepReviewWorkflowRelationController extends VerifyController
{
    private $stepReviewWorkflowRelationService;

    public function __construct()
    {
        parent::__construct();
        $this->stepReviewWorkflowRelationService = new stepReviewWorkflowRelationService();
    }

    /**
     * 查询审核流匹配数据树
     * @param Request $request
     * @return \think\Response
     */
    public function selectReviewRelationTree(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->stepReviewWorkflowRelationService->selectReviewRelationTree($param['filter'], $param['page']);
        return json(success_response('OK', $res));
    }

    /**
     * 查询审核流匹配数据树
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function selectProjectTemplateStepWorkflowReviewRelationTree(Request $request)
    {
        $param = $request->param()['param'];
        $projectTemplateId = $param['filter']['project_template_id'];
        $stepWorkflowId = $param['filter']['step_workflow_id'];
        $res = $this->stepReviewWorkflowRelationService->selectProjectTemplateStepWorkflowReviewRelationTree($projectTemplateId, $stepWorkflowId);
        return json(success_response('OK', $res));
    }

    /**
     * 保存所有审核配置数据
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function saveAllReviewData(Request $request)
    {
        $checkListRoleData = $request->param()['check_list_role_data'] ?? [];
        $reviewRelationData = $request->param()['review_relation_data'] ?? [];
        $res = [];
        $validate = new StepReviewWorkflowRelation();

        if (!empty($reviewRelationData)) {
            $validate->scene('SaveProjectTemplateReviewRelationItem');
            foreach ($reviewRelationData as $data) {
                if (!$validate->check($data)) {
                    throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
                }
            }
            $res['review_relation_update'] = $this->stepReviewWorkflowRelationService->saveProjectTemplateReviewRelation($reviewRelationData);
        }
        if (!empty($checkListRoleData)) {
            $validate->scene('SaveCheckListRoleCodeItem');
            foreach ($checkListRoleData as $data) {
                if (!$validate->check($data)) {
                    throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
                }
            }
            $res['check_list_update'] = $this->stepReviewWorkflowRelationService->saveCheckListRoleCode($checkListRoleData);
        }
        return json(success_response('OK', $res));
    }
}
